/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.pigeon.controllers;

import java.util.List;
import java.util.Map;
import org.seppiko.commons.utils.Base64Util;
import org.seppiko.pigeon.exceptions.PigeonCheckException;
import org.seppiko.pigeon.models.ControllerResponseEntity;
import org.seppiko.pigeon.models.ImapConfigEntity;
import org.seppiko.pigeon.models.ResponseMessageEntity;
import org.seppiko.pigeon.services.MailService;
import org.seppiko.pigeon.utils.JsonUtil;
import org.seppiko.pigeon.utils.MailUtil;
import org.seppiko.pigeon.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Leonard Woo
 */
@RestController
public class ImapController {

  @Autowired
  private MailService mailService;

  @GetMapping(value = "/imap")
  public ResponseEntity<byte[]> imapGetContentHandleExecution (
      @RequestHeader(required = false) Map<String, String> headers) {
    ControllerResponseEntity resp;
    if (headers == null || !headers.containsKey("Authorization")) {
      resp = ResponseUtil.generatorResponse(401,
          new ResponseMessageEntity(401, "Failed to obtain authorization"));
    } else {
      String authorization = headers.get("Authorization").split(" ")[1];
      String[] account = new String(Base64Util.decode(authorization)).split(":");

      List<ImapConfigEntity> configs = mailService.queryImapConfigList(account[0], account[1]);
      if (configs != null && configs.size() > 0) {
        resp = ResponseUtil.generatorResponse(200, JsonUtil.toJson(configs));
      } else {
        resp = ResponseUtil.generatorResponse(404,
            new ResponseMessageEntity(404, "Not found any IMAP configuration"));
      }
    }
    return ResponseUtil.sendResponse(resp);
  }

  @PostMapping(value = "/imap")
  public ResponseEntity<byte[]> imapPostContentHandleExecution (
      @RequestHeader(required = false) Map<String, String> headers,
      @RequestBody(required = false) String requestBody) {
    if (requestBody == null) {
      requestBody = "{}";
    }
    ImapConfigEntity config = JsonUtil.fromJson(requestBody, ImapConfigEntity.class);
    ControllerResponseEntity resp;
    if (headers == null || !headers.containsKey("Authorization")) {
      resp = ResponseUtil.generatorResponse(401,
          new ResponseMessageEntity(401, "Failed to obtain authorization"));
    } else if(config == null) {
      resp = ResponseUtil.generatorResponse(400,
          new ResponseMessageEntity(400, "You must commit a valid IMAP config"));
    } else {
      String authorization = headers.get("Authorization").split(" ")[1];
      String[] account = new String(Base64Util.decode(authorization)).split(":");
      try {
        MailUtil.checker(config.getHost(), config.getPort(), config.getUsername(), config.getPassword(),
            config.getImapAuth(), config.getImapTlsEnable(), config.getImapStartTlsEnable(),
            config.getImapStartTlsRequired());
        if(mailService.addImapConfig(config, account[0], account[1])) {
          // success
          resp = ResponseUtil.generatorResponse(200,
              new ResponseMessageEntity(200, "IMAP configuration added successfully"));
        } else {
          // failure
          resp = ResponseUtil.generatorResponse(200,
              new ResponseMessageEntity(400, "IMAP configuration failed to add"));
        }
      } catch (PigeonCheckException e) {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(400, e.getMessage()));
      }
    }
    return ResponseUtil.sendResponse(resp);
  }

  @PutMapping(value = "/imap")
  public ResponseEntity<byte[]> imapPutContentHandleExecution (
      @RequestHeader(required = false) Map<String, String> headers,
      @RequestBody(required = false) String requestBody) {
    if (requestBody == null) {
      requestBody = "{}";
    }
    ImapConfigEntity newConfig = JsonUtil.fromJson(requestBody, ImapConfigEntity.class);
    ControllerResponseEntity resp;
    if (headers == null || !headers.containsKey("Authorization")) {
      resp = ResponseUtil.generatorResponse(401,
          new ResponseMessageEntity(401, "Failed to obtain authorization"));
    } else if (newConfig == null || newConfig.getId() < 1) {
      // Not found
      resp = ResponseUtil.generatorResponse(404,
          new ResponseMessageEntity(404, "Not found need update configuration"));
    }  else {
      String authorization = headers.get("Authorization").split(" ")[1];
      String[] account = new String(Base64Util.decode(authorization)).split(":");
      if (newConfig.getHost() != null && MailUtil.hostCheck(newConfig.getHost()) != null) {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(400, "host is NOT a valid address"));
      } else if (newConfig.getPort() != null && !MailUtil.portCheck(newConfig.getPort())) {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(400, "port must be between 0 and 65535"));
      } else if (mailService.updateImapConfig(newConfig, account[0], account[1])) {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(200, "Update successfully"));
      } else {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(400, "Not found any IMAP configuration"));
      }
    }
    return ResponseUtil.sendResponse(resp);
  }

  @DeleteMapping(value = "/imap/{id}")
  public ResponseEntity<byte[]> imapDeleteContentHandleExecution (
      @RequestHeader(required = false) Map<String, String> headers,
      @PathVariable(name = "id", required = false) Integer id) {
    ControllerResponseEntity resp;
    if (headers == null || !headers.containsKey("Authorization")) {
      resp = ResponseUtil.generatorResponse(401,
          new ResponseMessageEntity(401, "Failed to obtain authorization"));
    } else if (id == null) {
      resp = ResponseUtil.generatorResponse(404,
          new ResponseMessageEntity(404, "Not found need delete configuration"));
    } else {
      String authorization = headers.get("Authorization").split(" ")[1];
      String[] account = new String(Base64Util.decode(authorization)).split(":");

      if(mailService.deleteImapConfig(id, account[0])) {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(200, "Delete successfully"));
      } else {
        resp = ResponseUtil.generatorResponse(200,
            new ResponseMessageEntity(400, "Failed to delete"));
      }
    }
    return ResponseUtil.sendResponse(resp);
  }
}
